<?php

/**
 * Services
 *
 * @package Controllers
 * @author  Vu Tran <vutran@perselab.com>
 * @since   Version 1.0
 */
// Models
require_once './models/User.php';
require_once './models/Recipe.php';
require_once './models/Category.php';
require_once './models/Ingredient.php';
require_once './models/Step.php';
require_once './models/Image.php';

class Services
{
	public function CategoriesToXml($app)
	{
		$categories = Model::factory('Category')->find_many();

		//categoryMap: key=category.id value=recipe list of category
		$categoryMap = array();

		//recipeMap: key=recipe.id value=owner of the recipe
		$recipeMap = array();

		//ingredient: key=ingredient.id value=image list of ingredient
		$ingredientMap = array();

		foreach ($categories as $category) {
			$recipes = $category->recipes()->order_by_desc('id')->find_many();
			//$recipes = $category->recipes()->find_many();
			foreach ($recipes as $recipe) {
				//owner
				$owner = $recipe->owner()->find_one();

				//ingredients
				$ingredients = $recipe->ingredients()->find_many();
				foreach ($ingredients as $ingredient) {
					$ingredientImages = $ingredient->images()->find_many();
					$ingredientMap[$ingredient->id] = $ingredientImages;
				}

				//steps
				$steps = $recipe->steps()->find_many();

				//images
				$images = $recipe->images()->find_many();
				$r_categories = $recipe->categories()->find_many();
				//todo generate xml not completed more work on this. still need to apply
				//images, ingredients, steps
				$recipeMap[$recipe->id] = array('owner' => $owner, 'ingredients' => $ingredients, 'steps' => $steps, 'images' => $images,'categories'=>$r_categories);
			}
			$categoryMap[$category->id] = $recipes;
		}

		return $app->render('categories.xml', array('categories' => $categories, 'categoryMap' => $categoryMap, 'recipeMap' => $recipeMap, 'ingredientMap' => $ingredientMap), null, 'text/xml');
	}
	
	public function recipesToXml($app,$userId,$categoryId)
	{
		$recipes = array();
		
		if($userId && !$categoryId){
			$recipes = Model::factory('Recipe')->where_equal('user_id', $userId)->order_by_desc('id')->find_many();
			//$recipes = Model::factory('Recipe')->where_equal('user_id', $userId)->find_many();
		}else if($categoryId && !$userId){
			$category = Model::factory('Category')->find_one($categoryId);
			if( $category && count($category) > 0 ){
				$recipes = $category->recipes()->order_by_desc('id')->find_many();
				//$recipes = $category->recipes()->find_many();
			}
		}else if($categoryId && $userId){
			$category = Model::factory('Category')->find_one($categoryId);
			if( $category && count($category) > 0 ){
				$recipes = $category->recipes()->where_equal('user_id', $userId)->order_by_desc('id')->find_many();
				//$recipes = $category->recipes()->where_equal('user_id', $userId)->find_many();
			}
		}
		
		//recipeMap: key=recipe.id value=owner of the recipe
		$recipeMap = array();

		//ingredient: key=ingredient.id value=image list of ingredient
		$ingredientMap = array();
		
		foreach ($recipes as $recipe) {
				//owner
				$owner = $recipe->owner()->find_one();

				//ingredients
				$ingredients = $recipe->ingredients()->find_many();
				foreach ($ingredients as $ingredient) {
					$ingredientImages = $ingredient->images()->find_many();
					$ingredientMap[$ingredient->id] = $ingredientImages;
				}

				//steps
				$steps = $recipe->steps()->find_many();

				//images
				$images = $recipe->images()->find_many();
				$categories = $recipe->categories()->find_many();
				//todo generate xml not completed more work on this. still need to apply
				//images, ingredients, steps
				$recipeMap[$recipe->id] = array('owner' => $owner, 'ingredients' => $ingredients, 'steps' => $steps, 'images' => $images, 'categories' => $categories);
		}
			
		return $app->render('recipes.xml', array(
			'recipes' => $recipes,
			'recipeMap' => $recipeMap,
			'ingredientMap' => $ingredientMap
		), null, 'text/xml');
	}
	
	public function recipeDetailToXml($app,$recipeId){
		$recipe = Model::factory('Recipe')->where_equal('id', $recipeId)->find_one();
		$ingredientMap = array();
		$steps = array();
		$owner = array();
		$images = array();
		$ingredients = array();
		$categories = array();
		if($recipe instanceof Recipe){
			$ingredients = $recipe->ingredients()->find_many();
			foreach ($ingredients as $ingredient) {
				$ingredientImages = $ingredient->images()->find_many();
				$ingredientMap[$ingredient->id] = $ingredientImages;
			}
			//steps
			$steps = $recipe->steps()->find_many();
			$owner = $recipe->owner()->find_one();
			$images = $recipe->images()->find_many();
			$categories = $recipe->categories()->find_many();
		}
		
		return $app->render('recipe.xml', array(
			'recipe' => $recipe,
			'ingredients' => $ingredients,
			'ingredientMap' => $ingredientMap,
			'steps' => $steps,
			'owner' => $owner,
			'images' => $images,
			'categories' => $categories
		), null, 'text/xml');
	}
	
	public function searchToXml($app,$key){
		$recipes = array();
		//recipeMap: key=recipe.id value=owner of the recipe
		$recipeMap = array();
		//ingredient: key=ingredient.id value=image list of ingredient
		$ingredientMap = array();
		
		if($key != ''){
			$recipes = Model::factory('Recipe')->where_like('name', '%'.$key.'%')->order_by_desc('id')->find_many();
			//$recipes = Model::factory('Recipe')->where_like('name', '%'.$key.'%')->find_many();
			
			foreach ($recipes as $recipe) {
					//owner
					$owner = $recipe->owner()->find_one();
	
					//ingredients
					$ingredients = $recipe->ingredients()->find_many();
					foreach ($ingredients as $ingredient) {
						$ingredientImages = $ingredient->images()->find_many();
						$ingredientMap[$ingredient->id] = $ingredientImages;
					}
	
					//steps
					$steps = $recipe->steps()->find_many();
	
					//images
					$images = $recipe->images()->find_many();
					$categories = $recipe->categories()->find_many();
					//todo generate xml not completed more work on this. still need to apply
					//images, ingredients, steps
					$recipeMap[$recipe->id] = array('owner' => $owner, 'ingredients' => $ingredients, 'steps' => $steps, 'images' => $images, 'categories' => $categories);
			}
		}			
		return $app->render('recipes.xml', array(
			'recipes' => $recipes,
			'recipeMap' => $recipeMap,
			'ingredientMap' => $ingredientMap
		), null, 'text/xml');
	}
	
	public function addRecipe($app,$recipe_data){
		require_once "imageUploadController.php";
		//moi lam ma~ gia thoi
		// Start a transaction
		ORM::get_db()->beginTransaction();
		
		try{
			$recipe = Model::factory('Recipe')->create();
			$recipe->user_id = $recipe_data['user_id'];
			$recipe->name = $recipe_data['name'];
			$recipe->serving = $recipe_data['serving'];
			$recipe->create_at = date('Y-m-d H:i:s');
			$recipe->update_at = date('Y-m-d H:i:s');
			$recipe->save();
			
			//for
			foreach($recipe_data['category'] As $categoryId){
				$catg_recipe = ORM::for_table('category_recipe')->create();
				$catg_recipe->category_id = $categoryId;
				$catg_recipe->recipe_id = $recipe->id;
				$catg_recipe->save();
			}
			
			if( count($recipe_data['images'])>0 ){
				foreach($recipe_data['images'] As $file){
					$upload = new imageUpload();
					$image = $upload->upload($file);
					
					$image_recipe = ORM::for_table('image_recipe')->create();
					$image_recipe->image_id = $image->id;
					$image_recipe->recipe_id = $recipe->id;
					$image_recipe->save();
				}
			}
			
			// Commit a transaction
			ORM::get_db()->commit();
			//print $recipe->id;
			$recipe_new = Model::factory('Recipe')->where_equal('id', $recipe->id)->find_one();
			$ingredientMap = array();
			$steps = array();
			$owner = array();
			$images = array();
			$ingredients = array();
			$categories = array();
			if($recipe_new instanceof Recipe){
				$ingredients = $recipe_new->ingredients()->find_many();
				foreach ($ingredients as $ingredient) {
					$ingredientImages = $ingredient->images()->find_many();
					$ingredientMap[$ingredient->id] = $ingredientImages;
				}
				//steps
				$steps = $recipe_new->steps()->find_many();
				$owner = $recipe_new->owner()->find_one();
				$images = $recipe_new->images()->find_many();
				$categories = $recipe->categories()->find_many();
			}
			
			return $app->render('recipe.xml', array(
				'recipe' => $recipe_new,
				'ingredients' => $ingredients,
				'ingredientMap' => $ingredientMap,
				'steps' => $steps,
				'owner' => $owner,
				'images' => $images,
				'categories' => $categories
			), null, 'text/xml');
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '-1';
		}
	}
	
	public function updateRecipe($app,$recipe_data){
		require_once "imageUploadController.php";
		ORM::get_db()->beginTransaction();
		
		try{
			$recipe = Model::factory('Recipe')->find_one($recipe_data['recipe_id']);
			$recipe->name = $recipe_data['name'];
			$recipe->serving = $recipe_data['serving'];
			$recipe->update_at = date('Y-m-d H:i:s');
			$recipe->save();
			
			if( $recipe_data['category'] && count($recipe_data['category']) > 0 ){
				//delete category
				$category_recipe = ORM::for_table('category_recipe')->where_equal('recipe_id', $recipe_data['recipe_id'])->delete_many();
				
				foreach($recipe_data['category'] As $categoryId){
					$catg_recipe = ORM::for_table('category_recipe')->create();
					$catg_recipe->category_id = $categoryId;
					$catg_recipe->recipe_id = $recipe->id;
					$catg_recipe->save();
				}
			}
			
			if( count($recipe_data['images'])>0 ){
				foreach($recipe_data['images'] As $file){
					$upload = new imageUpload();
					$image = $upload->upload($file);
					
					$image_recipe = ORM::for_table('image_recipe')->create();
					$image_recipe->image_id = $image->id;
					$image_recipe->recipe_id = $recipe->id;
					$image_recipe->save();
				}
			}
			// Commit a transaction
			ORM::get_db()->commit();
			
			$recipe_new = Model::factory('Recipe')->where_equal('id', $recipe->id)->find_one();
			$ingredientMap = array();
			$steps = array();
			$owner = array();
			$images = array();
			$ingredients = array();
			$categories = array();
			if($recipe_new instanceof Recipe){
				$ingredients = $recipe_new->ingredients()->find_many();
				foreach ($ingredients as $ingredient) {
					$ingredientImages = $ingredient->images()->find_many();
					$ingredientMap[$ingredient->id] = $ingredientImages;
				}
				//steps
				$steps = $recipe_new->steps()->find_many();
				$owner = $recipe_new->owner()->find_one();
				$images = $recipe_new->images()->find_many();
				$categories = $recipe->categories()->find_many();
			}
			
			return $app->render('recipe.xml', array(
				'recipe' => $recipe_new,
				'ingredients' => $ingredients,
				'ingredientMap' => $ingredientMap,
				'steps' => $steps,
				'owner' => $owner,
				'images' => $images,
				'categories' => $categories
			), null, 'text/xml');
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print $e;
		}
	}
	
	public function addIngredient($app,$ingredient_data){
		require_once "imageUploadController.php";

		ORM::get_db()->beginTransaction();
		
		try{
			$ingredient = Model::factory('Ingredient')->create();
			$ingredient->recipe_id = $ingredient_data['recipe_id'];
			$ingredient->name = $ingredient_data['name'];
			$ingredient->description = $ingredient_data['description'];
			$ingredient->quantity = $ingredient_data['quantity'];
			$ingredient->unit = $ingredient_data['unit'];
			$ingredient->create_at = date('Y-m-d H:i:s');
			$ingredient->update_at = date('Y-m-d H:i:s');
			$ingredient->save();
			
			if($ingredient_data['images'] != null){
				$upload_2 = new imageUpload();
				$image_ingr = $upload_2->upload($ingredient_data['images']);
				
				$image_ingredient = ORM::for_table('image_ingredient')->create();
				$image_ingredient->image_id = $image_ingr->id;
				$image_ingredient->ingredient_id = $ingredient->id;
				$image_ingredient->save();
			}
			// Commit a transaction
			ORM::get_db()->commit();
			
			$recipe_new = Model::factory('Recipe')->where_equal('id', $ingredient_data['recipe_id'])->find_one();
			$ingredientMap = array();
			$steps = array();
			$owner = array();
			$images = array();
			$ingredients = array();
			$categories = array();
			if($recipe_new instanceof Recipe){
				$ingredients = $recipe_new->ingredients()->find_many();
				foreach ($ingredients as $ingredientItem) {
					$ingredientImages = $ingredientItem->images()->find_many();
					$ingredientMap[$ingredientItem->id] = $ingredientImages;
				}
				//steps
				$steps = $recipe_new->steps()->find_many();
				$owner = $recipe_new->owner()->find_one();
				$images = $recipe_new->images()->find_many();
				$categories = $recipe_new->categories()->find_many();
			}
			
			return $app->render('recipe.xml', array(
				'recipe' => $recipe_new,
				'ingredients' => $ingredients,
				'ingredientMap' => $ingredientMap,
				'steps' => $steps,
				'owner' => $owner,
				'images' => $images,
				'categories' => $categories
			), null, 'text/xml');
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '-1';
		}
	}
	
	public function addStep($app,$steps_data){
		require_once "imageUploadController.php";
		//moi lam ma~ gia thoi
		// Start a transaction
		ORM::get_db()->beginTransaction();
		
		try{
			$step = Model::factory('Step')->create();
			$step->recipe_id = $steps_data['recipe_id'];
			$step->name = $steps_data['name'];
			$step->description = $steps_data['description'];
			$step->note = $steps_data['note'];
			$step->order = 1;
			$step->create_at = date('Y-m-d H:i:s');
			$step->update_at = date('Y-m-d H:i:s');
			$step->save();
			
			/*$upload_3 = new imageUpload();
			$image_st = $upload_3->upload($steps_data['images']);
			
			$image_step = ORM::for_table('image_step')->create();
			$image_step->image_id = $image_st->id;
			$image_step->step_id = $step->id;
			$image_step->save();*/
			
			// Commit a transaction
			ORM::get_db()->commit();
			
			$recipe_new = Model::factory('Recipe')->where_equal('id', $steps_data['recipe_id'])->find_one();
			$ingredientMap = array();
			$steps = array();
			$owner = array();
			$images = array();
			$ingredients = array();
			$categories = array();
			if($recipe_new instanceof Recipe){
				$ingredients = $recipe_new->ingredients()->find_many();
				foreach ($ingredients as $ingredientItem) {
					$ingredientImages = $ingredientItem->images()->find_many();
					$ingredientMap[$ingredientItem->id] = $ingredientImages;
				}
				//steps
				$steps = $recipe_new->steps()->find_many();
				$owner = $recipe_new->owner()->find_one();
				$images = $recipe_new->images()->find_many();
				$categories = $recipe_new->categories()->find_many();
			}
			
			return $app->render('recipe.xml', array(
				'recipe' => $recipe_new,
				'ingredients' => $ingredients,
				'ingredientMap' => $ingredientMap,
				'steps' => $steps,
				'owner' => $owner,
				'images' => $images,
				'categories' => $categories
			), null, 'text/xml');
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '-1';
		}
	}
	
	public function deleteRecipe($app,$recipe_data){		
		ORM::get_db()->beginTransaction();
		
		try{
			$recipe = Model::factory('Recipe')->find_one($recipe_data['recipe_id']);
			
			//delete category
			$category_recipe = ORM::for_table('category_recipe')->where_equal('recipe_id', $recipe_data['recipe_id'])->delete_many();

			//delete image recipe
			$image_recipe = ORM::for_table('image_recipe')->where_equal('recipe_id', $recipe_data['recipe_id'])->delete_many();
			
			//steps
			$steps = $recipe->steps()->find_many();
			//delete step
			if($steps && count($steps) > 0){
				foreach( $steps As $step){
					$image_steps = ORM::for_table('image_step')->where_equal('step_id', $step->id)->delete_many();
					$step->delete();
				}
			}

			//delete ingredient
			$ingredients = $recipe->ingredients()->find_many();
			if($ingredients && count($ingredients) > 0){
				foreach ($ingredients as $ingredient) {
					$image_ingredients = ORM::for_table('image_ingredient')->where_equal('ingredient_id', $ingredient->id)->delete_many();
					$ingredient->delete();
				}
			}
			
			$recipe->delete();
			
			ORM::get_db()->commit();
			
			print '1';
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '0';
		}
	}
	
	public function deleteRecipeIngredient($app,$recipe_data){		
		ORM::get_db()->beginTransaction();
		
		try{
			$recipe = Model::factory('Recipe')->find_one($recipe_data['recipe_id']);
			
			$ingredient = Model::factory('Ingredient')->find_one($recipe_data['ingredient_id']);
			$image_ingredients = ORM::for_table('image_ingredient')->where_equal('ingredient_id', $ingredient->id)->delete_many();
			$ingredient->delete();
					
			ORM::get_db()->commit();
			
			print '1';
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '0';
		}
	}
	
	public function deleteRecipeStep($app,$recipe_data){		
		ORM::get_db()->beginTransaction();
		
		try{
			$recipe = Model::factory('Recipe')->find_one($recipe_data['recipe_id']);
			
			$step = Model::factory('Step')->find_one($recipe_data['step_id']);
			$image_ingredients = ORM::for_table('image_step')->where_equal('step_id', $step->id)->delete_many();
			$step->delete();
					
			ORM::get_db()->commit();
			
			print '1';
			
		}catch (Exception $e){
			// Roll back a transaction
			ORM::get_db()->rollBack();
			print '0';
		}
	}
	
}